package com.example.dmallOrder.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dmall.sdk.DefaultDmallClient;
import com.dmall.sdk.DmallClient;
import com.dmall.sdk.request.dmall.DmallTradeOrderInfoGetRequest;
import com.dmall.sdk.response.dmall.DmallTradeOrderInfoGetResponse;
import com.example.dmallOrder.config.DmallConfig.DmallConstant;
import com.example.dmallOrder.config.cache.TiktokAccessTokenCacheEnum;
import com.example.dmallOrder.config.cache.TiktokCacheManager;

import com.example.dmallOrder.entity.DmallMsgOrder;
import com.example.dmallOrder.service.DmallMsgOrderService;
import com.google.gson.Gson;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@RestController
@RequestMapping("/v1/dmall")
@RequiredArgsConstructor
public class GmdmallController {
    @Resource
    TiktokCacheManager tiktokCacheManager;
    @Resource
    DmallMsgOrderService dmallMsgOrderService;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
//    @PostMapping("/v1/dmall_msg_trade_orderfinish")
//    @ResponseBody
//    public Map<String, String> dmallMsgTradeOrderFinish(@RequestBody Map<String, ?> requestBody) throws Exception {
//        String Uuid = UUID.fastUUID().toString();
//        TreeMap<String, ?> signParams = new TreeMap<>(requestBody);
//        signParams.remove("sign");
//        String sing = sign(signParams, DmallConstant.APP_SECRET.getValue());
//        Map<String, String> response = new HashMap<>();
////        if (!sing.equals(requestBody.get("sign"))) {
////            response.put("message", "no");
////            return response;
////        }
//        DmallMQResponse message = BeanUtil.toBeanIgnoreCase(requestBody, DmallMQResponse.class, false);
//        DmallMsgTradeOrderfinish dmallMsgTradeOrderfinish = BeanUtil.copyProperties(message.getMessage(), DmallMsgTradeOrderfinish.class);
//        DmallMsgTradeOrderfinish orderfinish = JSON.to(DmallMsgTradeOrderfinish.class, message.getMessage());
//        orderfinish.setMessageId(message.getMessageId());
//        String token =tiktokCacheManager.getCache(TiktokCacheManagerEnum.AccessCache, TiktokAccessTokenCacheEnum.AccessToken.getCode());
//        DmallClient dmallClient = new DefaultDmallClient(DmallConstant.TOKEN_SERVER_URL.getValue(), token, DmallConstant.APP_KEY.getValue(), DmallConstant.APP_SECRET.getValue());
//        DmallTradeOrderInfoGetRequest request = new DmallTradeOrderInfoGetRequest();
//        request.setOrderId(orderfinish.getOrderId());
//        request.setTraceId(Uuid);
//        request.setSnapshotOrder(false);
//        DmallTradeOrderInfoGetResponse response1 = dmallClient.execute(request);
//        System.out.println(response1);
//        DmallTradeOrderInfoGet orderInfoGet = dmallClient.execute(request,DmallTradeOrderInfoGet.class);
//
//        response.put("message", "ok");
//        return response;
//
//    }
//    /v1/dmall/dmallOrders/out


    @PostMapping("/dmallOrders/out")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> Orders(@RequestBody Map<String, ?> requestBody) throws Exception {
        TreeMap<String, ?> signParams = new TreeMap<>(requestBody);
        log.info("【下发出库订单 start】");
        signParams.remove("sign");
        String sing = sign(signParams, DmallConstant.APP_SECRET.getValue());
        log.info(StrFormatter.format("【下发出库订单 我方签名】：{}"),sing);
        Map<String, String> response = new HashMap<>();
        log.info(StrFormatter.format("【下发出库订单 签名】：{}"),requestBody.get("sign"));
        if (sing.equals(requestBody.get("sign"))) {

            Gson gson = new Gson();
            String msg = gson.toJson(requestBody);
            System.out.println(msg);
            DmallMsgOrder msgOrder = new DmallMsgOrder();
            msgOrder.setType("01");
            msgOrder.setMessage(msg);
            dmallMsgOrderService.save(msgOrder);
            response.put("message", "ok");
            //如需反馈结果则定义data
            JSONObject data = new JSONObject();
            data.put("msg", "成功");
            response.put("data", data.toJSONString());
            log.info("推送成功，messageId："+requestBody.get("messageId"));
            log.info(StrFormatter.format("【下发出库订单】end，返回结果:{}",response.toString()));
            return response;
        } else {
            response.put("message", "no");
            return response;
        }
    }


    @PostMapping("/dmallOrders/in")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> InOrder(@RequestBody Map<String, ?> requestBody) throws Exception {
        TreeMap<String, ?> signParams = new TreeMap<>(requestBody);
        log.info("【下发入库订单 start】");
        signParams.remove("sign");
        String sing = sign(signParams, DmallConstant.APP_SECRET.getValue());
        log.info(StrFormatter.format("【下发入库订单 我方签名】：{}"),sing);
        Map<String, String> response = new HashMap<>();
        log.info(StrFormatter.format("【下发入库订单 签名】：{}"),requestBody.get("sign"));
        if (sing.equals(requestBody.get("sign"))) {

            Gson gson = new Gson();
            String msg = gson.toJson(requestBody);
            System.out.println(msg);
            DmallMsgOrder msgOrder = new DmallMsgOrder();
            msgOrder.setType("01");
            msgOrder.setMessage(msg);
            dmallMsgOrderService.save(msgOrder);
            response.put("message", "ok");
            //如需反馈结果则定义data
            JSONObject data = new JSONObject();
            data.put("msg", "成功");
            response.put("data", data.toJSONString());
            log.info("推送成功，messageId："+requestBody.get("messageId"));
            log.info(StrFormatter.format("【下发入库订单】end，返回结果:{}",response.toString()));
            return response;
        } else {
            response.put("message", "no");
            return response;
        }
    }



//    @PostMapping("/onMessage")
//    @ResponseBody
//    public Map<String, String> onMessage(@RequestBody Map<String, ?> requestBody) throws Exception {
//        TreeMap<String, ?> signParams = new TreeMap<>(requestBody);
//        signParams.remove("sign");
//        String sing = sign(signParams, DmallConstant.APP_SECRET.getValue());
//        Map<String, String> response = new HashMap<>();
//        if (sing.equals(requestBody.get("sign"))) {
//            response.put("message", "ok");
//            //如需反馈结果则定义data
//            JSONObject data = new JSONObject();
//            data.put("example", "中国");
//            response.put("data", data.toJSONString());
//            return response;
//        } else {
//            response.put("message", "no");
//            return response;
//        }
//
//    }


    public static String sign(TreeMap<String, ?> params, String appSecret) throws Exception {
        String stringToSign = buildSignString(params);
        return hamcThenBase64(stringToSign.getBytes(StandardCharsets.UTF_8), appSecret);
    }

    private static String buildSignString(TreeMap<String, ?> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> entry : params.entrySet()) {
            if (entry.getKey() != null && entry.getValue() != null) {
                sb.append(entry.getKey()).append(entry.getValue());
            }
        }
        return sb.toString().toUpperCase();
    }

    private static String hamcThenBase64(byte[] bytes, String secret) throws Exception {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
        byte[] bs = hmacSha256.doFinal(bytes);
        return Base64.encodeBase64String(bs);
    }

}
